from png import Writer as PngWriter

from fenrispunk_tools.config import get_sprite_length, get_image
from fenrispunk_tools.utils.standard import get_datetime_stamp


def get_default_tile(sprite_length):
    colour_space = 255
    if colour_space < sprite_length or sprite_length < 1:
        raise ArithmeticError(
            "Default tile only works for squares between 1 and 255 pixels per side."
        )

    ratio = colour_space // sprite_length
    width = sprite_length
    height = sprite_length
    img = []
    for y in range(height):
        row = []
        for x in range(width):
            red = x * ratio
            green = y * ratio
            blue = max(0, colour_space - red - green)
            row.append(red)
            row.append(green)
            row.append(blue)
        img.append(tuple(row))
    return img


def get_rgb_image_data(image_data):
    # return [(1,1,1),(1,1,1)]
    return get_image(image_data)


def generate_tile_defaults(
    outfile=None, image_data=None, sprite_length=get_sprite_length()
):
    # TODO: Validate the path and/or create parent directories.
    generate_tile(
        outfile or f"var/fenrispunk_tools_screenshot_{get_datetime_stamp()}.png",
        get_default_tile(sprite_length)
        if not image_data
        else get_rgb_image_data(image_data),
        greyscale=False,
    )


def get_width(image_data):
    return len(image_data[0]) // 3


def get_height(image_data):
    return len(image_data)


def generate_tile(outfile, image_data, greyscale):
    with open(outfile, "wb") as file_out:
        png_writer = PngWriter(
            get_width(image_data), get_height(image_data), greyscale=greyscale
        )
        png_writer.write(file_out, image_data)
